package com.yny.administrator.android1607_meishi.utils;

import com.yny.administrator.android1607_meishi.bean.Movie;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 *         网络访问工具类
 */
public class HttpUtils {

    private static ByteArrayOutputStream baos;
    private static String name = null;

    public static byte[] getHttpUtilsRes(String path) throws IOException {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setDoInput(true);
        if (conn.getResponseCode() == 200) {
            InputStream is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        }
        return null;
    }

    public static List<Movie> getJsonRes(String path) throws IOException, JSONException {
        byte[] bytes = getHttpUtilsRes(path);
        String json = new String(bytes);
        JSONArray array = new JSONArray(json);
        List<Movie> list = new ArrayList<Movie>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            String recommend_caption = object.getString("recommend_caption");
            String recommend_cover_pic = object.getString("recommend_cover_pic");
            String type = object.getString("type");
            if (type.equals("scheme")) {
                Movie movie = new Movie(recommend_caption,recommend_cover_pic, String.valueOf(2), "hhh", type);
                list.add(movie);
            } else {
                JSONObject media = object.getJSONObject("media");
                String url = media.getString("url");
                String likes_count = media.getString("likes_count");
                Movie movie = new Movie(recommend_caption, recommend_cover_pic, likes_count, url, type);
                list.add(movie);
            }
        }
        return list;
    }
}
